package com.haruhi.service.impl;

import com.haruhi.entity.FileDetail;
import com.haruhi.entity.vo.ResponseEntity;
import com.haruhi.mapper.FileDetailMapper;
import com.haruhi.service.FileDetailService;
import com.haruhi.utils.FileUtil;
import com.haruhi.utils.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

@Service
public class FileDetailServiceImpl implements FileDetailService {

    @Autowired
    private FileDetailMapper fileDetailMapper;
    @Autowired
    private FileUtil fileUtil;

    @Value("${fileConfig.filePath}")
    private String filePath;
    /**
     * 添加
     * @param detail
     * @return
     */
    @Override
    public Integer insert(FileDetail detail) {
        return fileDetailMapper.insert(detail);
    }

    @Override
    public List<FileDetail> getByCondition(FileDetail condition) {
        return fileDetailMapper.selectByCondition(condition);
    }

    @Override
    public Integer updateByCondition(FileDetail detail, FileDetail condition) {

        return fileDetailMapper.updateByCondition(detail,condition);
    }

    @Override
    public int deleteByMD5(String md5, boolean enable) {

        return fileDetailMapper.deleteByMD5(md5,enable);
    }

    @Override
    public int deleteFile(FileDetail detail) {
        int result = fileDetailMapper.deleteById(detail.getId(),true);
        String path = null;
        if(!ParamUtil.isEmpty(detail.getRealName())){
            path = detail.getRealName();
        }else if(!ParamUtil.isEmpty(detail.getName())){
            path = filePath + detail.getName();
        }
        if(!ParamUtil.isEmpty(path)){
            FileDetail condition = new FileDetail();
            condition.setMd5(detail.getMd5());
            condition.setEnabled(true);
            List<FileDetail> fileDetails = fileDetailMapper.selectByCondition(condition);
            // 该文件只有一行数据时
            if(null == fileDetails || fileDetails.size() == 0){
                fileUtil.deleteFile(detail.getRealName());
            }
        }
        return result;
    }

}
